package com.frogs.ucenter.controller;


import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frogs.component.permission.api.service.PermissionHelper;
import com.frogs.component.permission.entity.Menu;
import com.frogs.component.permission.entity.User;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.exception.BusinessException;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;


/**
 * User Controller
 */
@Controller
public class AdminController extends BaseController3{
	private Logger log = Logger.getLogger( getClass() );

	@Resource(name = "permissionHelper")
	private PermissionHelper permissionHelper;
	
    private static final String LOGIN = "/login";
	
	
	private final static String LOGON = "/logon";

    private static final String INDEX = "/index";

	private static final String INDEX_VIEW = "index";

    private static final String LOGON_VIEW = "login";

    private static final String LOGOUT = "/admin/logout";


    private final static String REDIRECT_LOGON = "redirect:/admin/logon";

    private static final int TOP_MENU = 1040;

    private static final int ORG_TYPE_ID = 0;

    /**
     * 用户登陆注销日志
     */
    private void doLog(PermissionHelper p, User user, String opercode) {
        log.info("[" + opercode + "] userid:" + user.getUserId() + " username:" + user.getAccount() + " org:" + user.getOrgId());
        p.asyncLog(opercode, "user", user.getUserId().toString(), user.getOrgId() + ":" + user.getAccount(), "OK");
    }


    @RequestMapping(LOGON)
    public String logon(HttpServletRequest request){

        HttpRequestInfo httpRequest = new HttpRequestInfo(request);
        String retUrl = httpRequest.getParameter("retUrl");
        String url = httpRequest.getParameter("jsp");

        request.setAttribute("ReturnUrl", retUrl);

        if(!StringUtil.isEmpty(url)){
            return url ;
        }
        return LOGON_VIEW;
    }


    @RequestMapping(LOGIN)
    public String login(HttpServletRequest request, HttpServletResponse response) throws BusinessException {

        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String validCode = reqInfo.getParameter("validCode", "");
        String eqOrgAccount = reqInfo.getParameter("eqOrgAccount", "ehaoyao");
        String eqAccount = reqInfo.getParameter("eqAccount", "admin");
        String eqPassword = reqInfo.getParameter("eqPassword", "");
        String returnUrl = "redirect:"+ reqInfo.getParameter("retUrl", INDEX);

        this.verify(request, validCode, eqOrgAccount, eqAccount, eqPassword);
        log.info("verify after...");

        
        log.info(eqOrgAccount.toLowerCase()+","+eqAccount.toLowerCase()+","+eqPassword);
        permissionHelper.init(request, response);
        User user = permissionHelper.login(eqOrgAccount.toLowerCase(), eqAccount.toLowerCase(), eqPassword);

        if (user == null) {
            throw new BusinessException("user.login.username.not.exist");
        }
        // 判断用户是否被冻结的用户
        if (!user.isActive()) {
            throw new BusinessException("user.login.user.freeze");
        }
        if (user != null) {
            this.doLog(permissionHelper, user, "LOGIN");
        }
        return returnUrl;

    }


    @RequestMapping(LOGOUT)
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String view = REDIRECT_LOGON;
        permissionHelper.init(request, response);

        User user = permissionHelper.getUser();
        if (user != null) {
            doLog(permissionHelper, user, "LOGOUT");
        }
        permissionHelper.logout();
        return view;
    }

    private void verify(HttpServletRequest request, String validCode, String eqOrgAccount, String eqAccount, String eqPassword) throws BusinessException {
        if (StringUtil.isEmpty(eqAccount)) {
            throw new BusinessException("user.login.username.empty");
        }

        if (StringUtil.isEmpty(eqPassword)) {
            throw new BusinessException("user.login.userpassword.empty");
        }
    }
    
    @RequestMapping(INDEX)
	public String index(HttpServletRequest request,HttpServletResponse response,ModelMap model) throws Exception {
//    	permissionHelper.init(request, response);

		setRequestModelMap(request, model, true);
		
		HttpRequestInfo reqInfo = new HttpRequestInfo(request);
		
		User user = permissionHelper.getUser();
		int menuId = reqInfo.getIntParameter( "menuId", TOP_MENU );
		
		String view = reqInfo.getParameter( "view", INDEX_VIEW );
		try {
			log.info("permissionHelper>"+permissionHelper);
			List<Menu> allMenus=permissionHelper.getMenuList(TOP_MENU,ORG_TYPE_ID);
			
			
			List<Menu> modelMenus = new ArrayList<Menu>();
		    Map<Integer,List<Menu>> subModelMenuMap = new LinkedHashMap<Integer, List<Menu>> ();
		    Map<Integer,List<Menu>> threeModelMenuMap = new LinkedHashMap<Integer,List<Menu>>();
				
		  //1层.
	        for(Menu menu:allMenus){
	        	if(menu.getParentId().intValue() == menuId ){
	                modelMenus.add(menu);
	                
	            }
	        }
	        
	        //2层.
	        for(Menu menu:modelMenus){
	            List<Menu> subList = new LinkedList<Menu>();
	            for(Menu mm :allMenus){
	                if(mm.getParentId().intValue() == menu.getMenuId().intValue()){
	                    subList.add(mm);
	                }
	            }
	            subModelMenuMap.put(menu.getMenuId(),subList);
	        }

	        //3层
            for (Map.Entry<Integer, List<Menu>> entry : subModelMenuMap.entrySet()) {
                List<Menu> subMenus = entry.getValue();
                for(Menu mmm:subMenus){
	                List<Menu> threeList = new LinkedList<Menu>();
	                for(Menu mmmm:allMenus){
	                    if(mmmm.getParentId().intValue() == mmm.getMenuId().intValue()){
	                        threeList.add(mmmm);
	                    }
	                }
	                threeModelMenuMap.put(mmm.getMenuId(),threeList);
	            }
            }

	        model.put("modelMenus",modelMenus);
	        model.put("subModelMenus",subModelMenuMap);
	        model.put("threeMenus",threeModelMenuMap);
			
			model.addAttribute( "admin", user);
			model.addAttribute( "view", view );
	        
		} catch (Exception e) {
			log.error("func[index] user[" + user.toString() + "] menuId[" + menuId + "] view[" + view + "] exception[" + e.getStackTrace() + "] desc[fail]");
		}
		return view;
	}

}






